<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <button id="connect">连接</button>
    <button id="send" disabled="true">发送数据</button> <br>
    从服务器接收的数据如下:<br>
    <span id="content"></span>
    <script>
        var connect = document.querySelector('#connect')
        var send = document.querySelector('#send')
        var content = document.querySelector('#content')
        var ws = null
        connect.onclick = function () {
            ws = new WebSocket('ws://localhost:9999')
            ws.onopen = () => {
                console.log('连接服务器成功')
                send.disabled = false
                ws.onmessage = msg => {
                    console.log('从服务器接收到了数据' + msg)
                    //收到信息为Blob类型时
                    if (msg.data instanceof Blob) {
                        let result = null;
                        const reader = new FileReader();
                        reader.readAsText(msg.data, "UTF-8");
                        reader.onload = (e) => {
                            //字符串和json格式
                            result = JSON.parse(reader.result);
                            //result = JSON.stringify(reader.result);
                            console.log('websocked收到', result);
                            content.innerHTML = result
                        }
                    } else {
                        content.innerHTML = msg.data
                    }
                }
                ws.onclose = e => {
                    console.log('服务器关闭了连接')
                    send.disabled = true
                }
            }
            send.onclick = function () {
                // ws.send(JSON.stringify({
                //     action: 'getData',
                //     socketType: 'trendData',
                //     chartName: 'trend',
                //     value: ''
                // }))
                ws.send(JSON.stringify({
                    action: 'themeChange',
                    socketType: 'themeChange',
                    chartName: '',
                    value: 'chalk'
                }))
            }
        }
    </script>
</body>

</html>